package com.controller;

import com.pojo.ManManufacturer;
import com.pojo.Shop;
import com.pojo.User;
import com.service.ManManufacturerService;
import com.service.ShopService;
import com.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("/shop")
public class ShopController {

    @Autowired
    private ShopService shopService;
    @Autowired
    private UserService userService;


    @GetMapping("/shopInfo")
    public String shopInfo(Model model, HttpSession session) {
        User user = (User) session.getAttribute("user");
        if (user == null){
            return "login";
        }
        user = userService.selectById(user.getId());
        if (user.getBuyManerId() == null){
            return "shop/shopInfoAdd";
        }
        Shop shop = shopService.findById(user.getBuyManerId());
        model.addAttribute("shop", shop);
        return "shop/shopInfo";
    }

    @PostMapping("/insert")
    public String insert(Shop shop, HttpSession session, RedirectAttributes redirectAttributes) {
        User user = (User) session.getAttribute("user");
        if (user == null){
            return "login";
        }
        shopService.insert(shop,user);
        redirectAttributes.addFlashAttribute("successMessage", "网店添加成功！");
        return "redirect:/shop/shopInfo";
    }

    @PostMapping("/update")
    public String update(Shop shop, RedirectAttributes redirectAttributes) {
        shopService.update(shop);
        redirectAttributes.addFlashAttribute("successMessage", "网店信息更新成功！");
        return "redirect:/shop/shopInfo";
    }

}
